/**
 * 用于检查路由是否包含token
 * 如果不存在，还不在/config/remitRouter中，则返回200/500 Token已过期
 * 如果存在，则解析token，把用户昵称加载在ctx.username中
 */
const jwt = require('jsonwebtoken'),
    {isTimestampExpired} = require('../utils/timestamp'),
    redis = require('../modules/redis')
async function guard(ctx, next) {
    let urlTmp = ctx.request.url
    let urlArr = urlTmp.split("?")
    let url = urlArr[0]
    let tokenString = ctx.request.headers["token"] || false

    // const staticWord = url.split("/")[1]
    // if (staticWord !== global.prefixString) return next()

    //不需要判断token的路由地址
    const remit = global.config.remit

    //从url中去掉路由前缀
    let prefixString = global.config.prefixString
    if (prefixString.length>0) prefixString = "/" + prefixString
    url = url.replace(prefixString, '');

    if(remit.indexOf(url) === -1){ //需要监测
        if (!tokenString){
            response(ctx, {
                "status": 200,
                "code": 444,
                "data": {},
                "msg": '请重新登陆'
            })
            return
        }

        const token = jwt.verify(tokenString, global.config.secret)

        // if (isTimestampExpired(token.exp)){
        if (!token){
            global.response(ctx, {
                "status": 200,
                "code": 444,
                "data": {},
                "msg": 'Token已过期'
            })
            return
        }
        if (global.config.redisOn){ //如果开启redis，则判断用户在redis中是否存在
            await redis.connect()
            let result = await redis.get(token.data)
            if (!result){
                global.response(ctx, {
                    "status": 200,
                    "code": 444,
                    "data": {},
                    "msg": 'Token已过期'
                })
                return
            }
        }
        ctx.username = token.data // console.log(ctx.username)
        ctx.timestamp = Date.now()
    }
    await next()
}

module.exports = guard